package cn.gjxblog.xa.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * @author gjx
 * @version v1.0
 * @Description
 * @date 2019/7/3 10:40
 */
@Configuration
@MapperScan(basePackages = FirstMybatisConfig.BASE_PACKAGE,sqlSessionTemplateRef = "sqlSessionTemplateOne")
public class FirstMybatisConfig {

    //mapper模式下的接口层
    static final String BASE_PACKAGE = "cn.gjxblog.xa.dao.one";

    static final String MAPPER_LOCATION = "classpath:mybatis/one/*.xml";

    @Bean("mybatisConfiguration")
    @ConfigurationProperties("mybatis.configuration")
    public  org.apache.ibatis.session.Configuration configuration(){
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        return configuration;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactoryOne(@Qualifier("dataSourceOne") DataSource dataSource,@Qualifier("mybatisConfiguration")org.apache.ibatis.session.Configuration configuration) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);

        //注入mybatis配置
        factoryBean.setConfiguration(configuration);
        factoryBean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION)
        );
        return factoryBean.getObject();
    }



    @Bean
    public SqlSessionTemplate sqlSessionTemplateOne(@Qualifier("sqlSessionFactoryOne") SqlSessionFactory factoryOne){
        SqlSessionTemplate template = new SqlSessionTemplate(factoryOne);
        return  template;
    }


}
